package jmc.util;

import java.lang.reflect.Constructor;
import java.lang.reflect.InvocationTargetException;
import java.util.HashMap;
import java.util.Map;


@SuppressWarnings("unchecked")
public class TypeUtils {
	
	private static final Map PRIMITIVE_NAME_TYPE_MAP = new HashMap();
	   
    static
	   {
	      PRIMITIVE_NAME_TYPE_MAP.put("boolean", Boolean.TYPE);
	      PRIMITIVE_NAME_TYPE_MAP.put("byte", Byte.TYPE);
	      PRIMITIVE_NAME_TYPE_MAP.put("char", Character.TYPE);
	      PRIMITIVE_NAME_TYPE_MAP.put("short", Short.TYPE);
	      PRIMITIVE_NAME_TYPE_MAP.put("int", Integer.TYPE);
	      PRIMITIVE_NAME_TYPE_MAP.put("long", Long.TYPE);
	      PRIMITIVE_NAME_TYPE_MAP.put("float", Float.TYPE);
	      PRIMITIVE_NAME_TYPE_MAP.put("double", Double.TYPE);
	      PRIMITIVE_NAME_TYPE_MAP.put("string", String.class);
	   }
    
	private static final Map CLASS_FOR_TYPE_MAP = new HashMap();
	   
    static
	   {
    	CLASS_FOR_TYPE_MAP.put("boolean", Boolean.class);
    	CLASS_FOR_TYPE_MAP.put("byte", Byte.class);
    	CLASS_FOR_TYPE_MAP.put("char", Character.class);
    	CLASS_FOR_TYPE_MAP.put("short", Short.class);
    	CLASS_FOR_TYPE_MAP.put("int", Integer.class);
    	CLASS_FOR_TYPE_MAP.put("long", Long.class);
    	CLASS_FOR_TYPE_MAP.put("float", Float.class);
    	CLASS_FOR_TYPE_MAP.put("double", Double.class);
    	CLASS_FOR_TYPE_MAP.put("string", String.class);
	   }
    
    public static Class getPrimitiveTypeForName(final String name)
    {
       return (Class) PRIMITIVE_NAME_TYPE_MAP.get(name);
    }
    
    public static Class getClassForName(final String name)
    {
       return (Class) CLASS_FOR_TYPE_MAP.get(name);
    }
    
    public static Object createObjectFrom(String value, String type){
       	try{
    		Class paramClass = getClassForName(type);
    		Class[] constructorParamType = {String.class};
    		Constructor c = paramClass.getConstructor(constructorParamType);
    		return c.newInstance(value);
    	} catch (InstantiationException ie){
    		ie.printStackTrace();
    		return null;
    	} catch (InvocationTargetException ite){
    		ite.printStackTrace();
    		return null;
    	} catch (IllegalAccessException iae) {
    		iae.printStackTrace();
    		return null;
    	} catch (NoSuchMethodException nsme) {
    		nsme.printStackTrace();
    		return null;
    	} 
   }
  

}
